<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElButton, ElTabs, ElTabPane, ElMessage, ElRow, ElCol } from 'element-plus'
import { Plus, Refresh } from '@element-plus/icons-vue'
import TaskItem from '@/components/TaskItem/index.vue'
import StatusCard from '@/components/StatusCard/index.vue'
import DataTable from '@/components/DataTable/index.vue'
import type { Task } from '@/types'
import { getTasks } from '@/utils/api'

const activeTab = ref('running')
const tasks = ref<Task[]>([])
const loading = ref(false)

const taskStats = reactive({
  total: 0,
  running: 0,
  completed: 0,
  failed: 0,
  pending: 0
})

const filteredTasks = computed(() => {
  switch (activeTab.value) {
    case 'running':
      return tasks.value.filter(task => task.status === 'running')
    case 'completed':
      return tasks.value.filter(task => task.status === 'completed')
    case 'failed':
      return tasks.value.filter(task => task.status === 'failed')
    case 'pending':
      return tasks.value.filter(task => task.status === 'pending')
    default:
      return tasks.value
  }
})

const tableColumns = [
  { key: 'name', label: '任务名称', sortable: true },
  { key: 'type', label: '任务类型', sortable: true },
  { key: 'status', label: '状态', sortable: true },
  { key: 'accountId', label: '目标账号', sortable: false, formatter: (row: Task) => row.accountId || '全部' },
  { key: 'deviceId', label: '执行设备', sortable: false, formatter: (row: Task) => row.deviceId || '自动分配' },
  { key: 'scheduledAt', label: '计划时间', sortable: true, formatter: (row: Task) => row.scheduledAt ? new Date(row.scheduledAt).toLocaleString() : '立即执行' },
  { key: 'progress', label: '进度', sortable: false, formatter: (row: Task) => row.progress ? `${row.progress.completed}/${row.progress.total}` : '0/0' }
]

onMounted(() => {
  loadTasks()
})

const loadTasks = async() => {
  loading.value = true
  try {
    const response = await getTasks()
    tasks.value = response.data || []
    updateStats()
  } catch (error) {
    ElMessage.error('加载任务列表失败')
    tasks.value = [
      {
        id: '1',
        name: '批量点赞任务',
        type: 'like',
        status: 'running',
        accountId: 'acc_001',
        deviceId: 'device_001',
        description: '对热门视频进行批量点赞',
        scheduledAt: Date.now(),
        startedAt: Date.now() - 300000,
        progress: { completed: 45, total: 100 },
        createdAt: Date.now() - 3600000
      },
      {
        id: '2',
        name: '内容发布任务',
        type: 'post',
        status: 'pending',
        accountId: 'acc_002',
        description: '发布预定的营销内容',
        scheduledAt: Date.now() + 3600000,
        progress: { completed: 0, total: 5 },
        createdAt: Date.now() - 1800000
      },
      {
        id: '3',
        name: '关注用户任务',
        type: 'follow',
        status: 'completed',
        accountId: 'acc_001',
        deviceId: 'device_002',
        description: '关注相关领域的用户',
        scheduledAt: Date.now() - 7200000,
        startedAt: Date.now() - 7200000,
        completedAt: Date.now() - 3600000,
        progress: { completed: 50, total: 50 },
        createdAt: Date.now() - 86400000
      },
      {
        id: '4',
        name: '评论互动任务',
        type: 'comment',
        status: 'failed',
        accountId: 'acc_003',
        deviceId: 'device_001',
        description: '在热门内容下进行评论互动',
        scheduledAt: Date.now() - 1800000,
        startedAt: Date.now() - 1800000,
        progress: { completed: 12, total: 30 },
        createdAt: Date.now() - 5400000
      }
    ]
    updateStats()
  } finally {
    loading.value = false
  }
}

const updateStats = () => {
  taskStats.total = tasks.value.length
  taskStats.running = tasks.value.filter(task => task.status === 'running').length
  taskStats.completed = tasks.value.filter(task => task.status === 'completed').length
  taskStats.failed = tasks.value.filter(task => task.status === 'failed').length
  taskStats.pending = tasks.value.filter(task => task.status === 'pending').length
}

const handleStart = async(task: Task) => {
  try {
    await updateTask(task.id, { ...task, status: 'running', startedAt: Date.now() })
    await loadTasks()
    ElMessage.success(`任务 ${task.name} 开始执行`)
  } catch (error) {
    ElMessage.error(`启动任务失败: ${error}`)
  }
}

const handlePause = async(task: Task) => {
  try {
    await updateTask(task.id, { ...task, status: 'paused' })
    await loadTasks()
    ElMessage.success(`任务 ${task.name} 已暂停`)
  } catch (error) {
    ElMessage.error(`暂停任务失败: ${error}`)
  }
}

const handleRestart = async(task: Task) => {
  try {
    const restartedTask = {
      ...task,
      status: 'running' as const,
      startedAt: Date.now(),
      completedAt: undefined,
      progress: { completed: 0, total: task.progress?.total || 0 }
    }
    await updateTask(task.id, restartedTask)
    await loadTasks()
    ElMessage.success(`任务 ${task.name} 重新开始执行`)
  } catch (error) {
    ElMessage.error(`重启任务失败: ${error}`)
  }
}

const handleDelete = async(task: Task) => {
  try {
    await deleteTask(task.id)
    await loadTasks()
    ElMessage.success(`任务 ${task.name} 删除成功`)
  } catch (error) {
    ElMessage.error(`删除任务失败: ${error}`)
  }
}

const handleDetails = (task: Task) => {
  ElMessage.info(`查看任务详情: ${task.name}`)
}

const handleAddTask = () => {
  ElMessage.info('创建新任务功能正在开发中...')
}

const handleRefresh = () => {
  loadTasks()
}

const handleRowClick = (task: Task) => {
  handleDetails(task)
}
</script>

<template>
  <div class="tasks-page">
    <div class="page-header">
      <h2>任务管理</h2>
      <div class="header-actions">
        <ElButton :icon="Refresh" @click="handleRefresh">刷新</ElButton>
        <ElButton type="primary" :icon="Plus" @click="handleAddTask">
          创建任务
        </ElButton>
      </div>
    </div>

    <!-- 任务统计 -->
    <ElRow :gutter="20" class="stats-row">
      <ElCol :xs="24" :sm="12" :md="6">
        <StatusCard
          title="任务总数"
          :value="taskStats.total"
          color="#409eff"
        />
      </ElCol>
      <ElCol :xs="24" :sm="12" :md="6">
        <StatusCard
          title="执行中"
          :value="taskStats.running"
          color="#67c23a"
          trend="up"
        />
      </ElCol>
      <ElCol :xs="24" :sm="12" :md="6">
        <StatusCard
          title="已完成"
          :value="taskStats.completed"
          color="#409eff"
          trend="neutral"
        />
      </ElCol>
      <ElCol :xs="24" :sm="12" :md="6">
        <StatusCard
          title="执行失败"
          :value="taskStats.failed"
          color="#f56c6c"
          trend="down"
        />
      </ElCol>
    </ElRow>

    <!-- 任务列表 -->
    <ElTabs v-model="activeTab" class="tasks-tabs">
      <ElTabPane label="执行中" name="running">
        <div class="tasks-grid">
          <ElRow :gutter="20">
            <ElCol
              v-for="task in filteredTasks"
              :key="task.id"
              :xs="24"
              :sm="12"
              :md="8"
              :lg="6"
              class="task-col"
            >
              <TaskItem
                :task="task"
                @start="handleStart"
                @pause="handlePause"
                @restart="handleRestart"
                @delete="handleDelete"
                @details="handleDetails"
              />
            </ElCol>
          </ElRow>
        </div>
      </ElTabPane>

      <ElTabPane label="待执行" name="pending">
        <div class="tasks-grid">
          <ElRow :gutter="20">
            <ElCol
              v-for="task in filteredTasks"
              :key="task.id"
              :xs="24"
              :sm="12"
              :md="8"
              :lg="6"
              class="task-col"
            >
              <TaskItem
                :task="task"
                @start="handleStart"
                @pause="handlePause"
                @restart="handleRestart"
                @delete="handleDelete"
                @details="handleDetails"
              />
            </ElCol>
          </ElRow>
        </div>
      </ElTabPane>

      <ElTabPane label="已完成" name="completed">
        <div class="tasks-grid">
          <ElRow :gutter="20">
            <ElCol
              v-for="task in filteredTasks"
              :key="task.id"
              :xs="24"
              :sm="12"
              :md="8"
              :lg="6"
              class="task-col"
            >
              <TaskItem
                :task="task"
                @start="handleStart"
                @pause="handlePause"
                @restart="handleRestart"
                @delete="handleDelete"
                @details="handleDetails"
              />
            </ElCol>
          </ElRow>
        </div>
      </ElTabPane>

      <ElTabPane label="执行失败" name="failed">
        <div class="tasks-grid">
          <ElRow :gutter="20">
            <ElCol
              v-for="task in filteredTasks"
              :key="task.id"
              :xs="24"
              :sm="12"
              :md="8"
              :lg="6"
              class="task-col"
            >
              <TaskItem
                :task="task"
                @start="handleStart"
                @pause="handlePause"
                @restart="handleRestart"
                @delete="handleDelete"
                @details="handleDetails"
              />
            </ElCol>
          </ElRow>
        </div>
      </ElTabPane>

      <ElTabPane label="全部任务" name="all">
        <DataTable
          :data="tasks"
          :columns="tableColumns"
          :loading="loading"
          :total="tasks.length"
          show-search
          show-refresh
          show-add
          add-text="创建任务"
          search-placeholder="搜索任务..."
          @refresh="handleRefresh"
          @add="handleAddTask"
          @row-click="handleRowClick"
        />
      </ElTabPane>
    </ElTabs>
  </div>
</template>

<style scoped lang="scss">
.tasks-page {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    
    h2 {
      margin: 0;
      color: var(--el-text-color-primary);
    }
    
    .header-actions {
      display: flex;
      gap: 12px;
    }
  }
  
  .stats-row {
    margin-bottom: 24px;
  }
  
  .tasks-tabs {
    .tasks-grid {
      .task-col {
        margin-bottom: 20px;
      }
    }
  }
}

@media (max-width: 768px) {
  .tasks-page {
    .page-header {
      flex-direction: column;
      align-items: stretch;
      gap: 16px;
      
      h2 {
        text-align: center;
      }
      
      .header-actions {
        justify-content: center;
      }
    }
  }
}
</style>